//
//  PhotoBrowserCell.swift
//  新浪微博
//
//  Created by 焦林生 on 15/11/19.
//  Copyright © 2015年 焦林生. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

//MARK: 照片查看cell代理
protocol PhotoBrowserCellDelegate: NSObjectProtocol {

   //图像视图将要关闭
    func photoBrowserCellShouldDismiss()
    
    //图像视图缩放
    func photoBrowserCellDidZoom(scale: CGFloat)
}

//照片查看cell
class PhotoBrowserCell: UICollectionViewCell {
    
    //定义代理
    weak var photoDelegate: PhotoBrowserCellDelegate?
    
    //MARK: 监听方法
    @objc private func tapImage() {
    
        photoDelegate?.photoBrowserCellShouldDismiss()
    }
    
    //图像URL
    var imageURL: NSURL? {
    
        didSet {
        
            guard let url = imageURL else {
            
                return
            }
            
            resetScrollView()
            
            //用缩略图当做占位视图
            let key = url.absoluteString
            //1> 从磁盘加载缩略图图像
            imageView.image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            setPlaceholder(imageView.image)
            
            placeholder.setNeedsDisplay()
            
            //2 异步加载大图
            imageView.sd_setImageWithURL(middleUrl(imageURL!),
                placeholderImage: nil,
                options: [SDWebImageOptions.RefreshCached,SDWebImageOptions.RetryFailed],
                progress: { (current, total) -> Void in
                    
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.placeholder.progress = CGFloat(current) / CGFloat(total)
                    })
                    
                }) { (image, error , _ , _) -> Void in
                    
                    if error != nil {
                    
                        SVProgressHUD.showInfoWithStatus("图片下载失败")
                        return 
                    }
                    
                    //隐藏占位图像
                    self.placeholder.hidden = true
                    
                    //设置图像视图的位置
                    self.setImagePosition(image)
                    
            }
        }
    
        
    }
    
    private func setPlaceholder(image: UIImage?) {
        
        //0 显示视图
        placeholder.hidden = false
        //1 设置图像
        placeholder.image = image
        //2 设置大小
        placeholder.sizeToFit()
        //3 设置中心点
        placeholder.center = scrollView.center
        
    }
    
    //重设scrollview内容属性
    private func resetScrollView() {
    
        //重设scrollView的形变参数
        imageView.transform = CGAffineTransformIdentity
        
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    /**
    创建大图URL
    
    - parameter url: 缩略图URL
    
    - returns: 中图URL
    */
    private func middleUrl(url: NSURL) ->NSURL {
        //1 转换成string(完全的字符串)
        var urlString = url.absoluteString
        
        //2 替换单词
        urlString = urlString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        
        return NSURL(string: urlString)!
    }
    /**
   MARK: 计算图像显示大小
    
    - parameter image: 图像
    
    - returns: 以scrollview宽度为基准的图像大小
    */
    private func displaySize(image: UIImage) -> CGSize {
    
        let w = scrollView.bounds.width
        let h = image.size.height * w / image.size.width
        
        return CGSize(width: w, height: h)
    }
    /**
    MARK: 设置图像位置
    
    - parameter image: 如果是长图  顶端对齐  如果是短图  居中对齐
    */
    private func setImagePosition(image: UIImage) {
    
        //1 计算图像大小
        let size = self.displaySize(image)
    
        
        //2 判断图像高度
        if size.height > scrollView.bounds.height {
        
            imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            scrollView.contentSize = size
        }else {
        
            imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            
            let y = (scrollView.bounds.height - size.height) * 0.5
            
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
        }
        
    }
    
    //MARK:构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 懒加载控件
    //滚动视图
     lazy var scrollView: UIScrollView = UIScrollView()
    
    //图像视图
     lazy var imageView: UIImageView = UIImageView()
    
    //占位图像
    private lazy var placeholder: ProgressImageView = ProgressImageView()
    
    private func setupUI() {
    
        //1 添加控件
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        scrollView.addSubview(placeholder)
        
        //2设置位置
        var rect = bounds
        rect.size.width -= 20
        scrollView.frame = rect
        
        //3 设置scrollView缩放
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
        
        //4 添加手势识别
        let tap = UITapGestureRecognizer(target: self, action: "tapImage")
        imageView.userInteractionEnabled = true
        imageView.addGestureRecognizer(tap)
        
    }
 
}
// MARK: - UIScrollViewDelegate
extension PhotoBrowserCell: UIScrollViewDelegate {

    //返回被缩放的视图
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    /**
    缩放完成后执行一次
    
    - parameter scrollView: scrollView
    - parameter view:       view被缩放的视图
    - parameter scale:      被缩放的比例
    */
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        //如果缩放比例小于1 通知控制器关闭界面
        if scale < 1 {
        
            photoDelegate?.photoBrowserCellShouldDismiss()
            return
        }
        
        //设置图片间距
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        offsetY = offsetY < 0 ? 0 : offsetY
        
        var offsetX  = (scrollView.bounds.width - view!.frame.width) * 0.5
        offsetX = offsetX < 0 ? 0 : offsetX
        
        //设置间距
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
    }
    
    //缩放比例
    func scrollViewDidZoom(scrollView: UIScrollView) {

        photoDelegate?.photoBrowserCellDidZoom(imageView.transform.a)
    }
    
    
}





